package com.cloud.encrypting_cloud_storage.global;

import com.cloud.encrypting_cloud_storage.exceptions.JsonException;
import com.cloud.encrypting_cloud_storage.exceptions.PageException;
import com.cloud.encrypting_cloud_storage.models.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author leon
 * @Description: TODO(统一异常处理)
 * @date 2022年04月20日 12:16
 */
@Slf4j
@ControllerAdvice
public class CustomExceptionHandler {
    /**
     * 默认错误视图
     */
    private static final String DEFAULT_VIEW = "error/error";

    /**
     * 统一 JSON 异常处理
     * @param jsonException
     * @return
     */
    @ExceptionHandler({JsonException.class})
    @ResponseBody
    public ApiResponse jsonErrorHandler(JsonException jsonException){
        return ApiResponse.ofException(jsonException);
    }

    /**
     * 统一 页面 异常处理
     * @param pageException
     * @return
     */
    @ExceptionHandler(value = {PageException.class})
    public ModelAndView pageErrorHandler(PageException pageException){
        log.error("[pageException]:{}",pageException.getMessage());
        ModelAndView mav = new ModelAndView(DEFAULT_VIEW);
        mav.addObject("message",pageException.getMessage());
        mav.addObject("code",pageException.getCode());
        return mav;
    }


}
